import requests  # 导入requests包
import re
from bs4 import BeautifulSoup
import os
import time
import random
from download_m3u8 import Download
import random
headers = {
'Sec-Ch-Ua-Mobile':'?1',
'Sec-Ch-Ua-Platform':'"Android"',
'User-Agent':'Mozilla/5.0 (Linux; Android 13; SM-A536E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36 uacq'
}

def decode_unicode_sequences(s):
    # 使用正则表达式查找 \\uXXXX 序列
    unicode_sequences = re.findall(r'\\u([0-9a-fA-F]{4})', s)

    # 遍历每个序列并尝试解码
    for seq in unicode_sequences:
        # 将 \\uXXXX 转换为 \uXXXX
        escaped_seq = '\\' + 'u' + seq
        # 使用 eval 安全地解码序列（这里假设输入是可信的）
        try:
            unicode_char = eval(f"'{escaped_seq}'")
            # 替换原始序列为解码后的字符
            s = s.replace(f'\\u{seq}', unicode_char)
        except UnicodeDecodeError:
            # 如果解码失败，保留原始序列
            pass

    return s


def remove_last_slash_content(url):
    # 使用rsplit('/', 1)来分割字符串，从右边开始分割，并且只分割一次
    # 这样会得到一个包含两部分的列表：最后一个'/'之前的部分和之后的部分
    parts = url.rsplit('/', 1)

    # 如果分割成功，则parts至少包含两个元素，parts[0]是最后一个'/'之前的部分
    if len(parts) == 2:
        return parts[0] + '/'
    else:
        # 如果url中没有'/'，则直接返回原始url
        return url


class Get_m3u8:
    dir = "F:\\media"
    def __init__(self):
        self.number = 2
        self.step = 1
        self.init_url_index()
        pass

    def init_url_index(self):
        if os.path.exists("get_url_index.txt") == False:
            fo = open("get_url_index.txt", "w+")
            fo.write(str(self.number))
            fo.close()

    def get_url_index(self):
        time.sleep( random.randint(1,10))
        fo = open("get_url_index.txt", "r+")
        data = fo.read(20)
        fo.close()
        print("当前网站遍历位置：", data)
        fo = open("get_url_index.txt", "w+")
        self.number = int(data) + 1
        fo.write(str(self.number))
        fo.close()

    def debug(self, *args):
        for value in args:
            print(value, end="")
        print("")

    def get_url(self, url='https://700kan.com/DyttPlay/61116-1-1.html'):
        info_str = ""
        try:
            #  self.debug(url)
            time.sleep(random.randint(0, 5))
            html_str = requests.get(url, headers = headers)
            #self.debug(html_str.text)
        except:
            print(url,"获取不到")
            return None

        try:
            matchObj = re.findall(r'<div class="module-info-tag-link"><(.*?)</a>', str(html_str.text))
            #print(matchObj)
            if matchObj:
                for str1 in matchObj:
                    searchObj = re.match(r'(.*?)>(.*)', str1)
                    if searchObj:
                        print("searchObj.group(1) : ", searchObj.group(2))
                        if searchObj.group(2) != "未知":
                            info_str += searchObj.group(2)
            else:
                print("找不到", "module-info-tag-link")

            matchObj = re.findall(r'<a href="(.*?)</a><span class="slash">/</span>', str(html_str.text))
            #print(matchObj)
            if matchObj:
                for str1 in matchObj:
                    searchObj = re.match(r'(.*?).html">(.*)', str1)
                    if searchObj:
                        print("searchObj.group(1) : ", searchObj.group(2))
                        if searchObj.group(2) != "未知":
                            info_str += searchObj.group(2)
            else:
                print("找不到", "module-info-tag-link")

            soup = BeautifulSoup(html_str.text, 'html.parser')
            # print(soup)
            emailid_regexp = re.compile("https:(.*)\.m3u8")
            first_email_id = soup.find(string=emailid_regexp)
            # print(first_email_id)

            matchObj = re.findall(r'https:(.*?)\.m3u8', first_email_id)
            tmp_m3u8_url = "https:" + str(matchObj[0]) + ".m3u8"
            # print("tmp_m3u8_url=", tmp_m3u8_url)
            tmp_m3u8_url = decode_unicode_sequences(tmp_m3u8_url)
            # print("tmp_m3u8_url=",tmp_m3u8_url)

            m3u8_url = tmp_m3u8_url.replace(r'\/', "/")
            ur_index = m3u8_url.find("\",\"")
            # print(ur_index)
            if ur_index > 1:
                m3u8_url = m3u8_url[:ur_index]

            emailid_regexp = re.compile("《(.*)》")
            first_email_id = soup.find(string=emailid_regexp)
            # print(first_email_id)
            matchObj = re.findall(r'《(.*)》', first_email_id)
            # print(matchObj)
            name = matchObj[0]
        except:
            return None
        #'https://700kan.com/DyttPlay/61116-1-1.html'
        searchObj = re.match(r'https://.*/\d+-\d+-(\d+).html', url)
        if searchObj:
            print("searchObj.group(1) : ", searchObj.group(1))
            index = searchObj.group(1)
            if index != "1":
                name += "-"+str(index)

        return name, m3u8_url, url, info_str

    def get_m3u8_url(self, number, index1):
        flag = 0

        for index2 in range(1, 50):
            while not os.path.exists(self.dir):#先判断保存的目录是否存在再往下执行
                print(f"目录{self.dir}不存在")
                time.sleep(60)

            url = f'https://700kan.com/DyttPlay/{number}-{index1}-{index2}.html'
            ret = self.get_url(url)
            if ret == None:
                if  self.step<100:
                    self.step += 1
                return flag
            else:
                print(f"{number}-{index1}-{index2}", ret)
                self.deal_url(ret,url)
                flag = 1
                self.step = 1

    def get_m3u8_url1(self, number):
        for index1 in range(1, 2):
            ret = self.get_m3u8_url(number, index1)
            if ret == 0:
                return

    def get_m3u8_url_auto(self):
        self.get_url_index()
        self.get_m3u8_url1(self.number)


    def loop(self):
        for i in range(1000000):
            self.get_m3u8_url_auto()

    def deal_url(self,ts_info,index_url):
        name, m3u8_url, url, info_str = ts_info
        try:
            if  "伦" in info_str :
                Download(url=m3u8_url, name=name, dir=self.dir, info=info_str,index_url=index_url)
        except:
            print( name, m3u8_url, url, info_str,"下载出错")

if __name__ == '__main__':
    m3u8 = Get_m3u8()
    m3u8.loop()
    #m3u8.get_m3u8_url_auto()
    # print(m3u8.get_m3u8_url_auto(url='https://700kan.com/DyttPlay/955-2-1.html'))
    #print(m3u8.get_m3u8_url_auto(url='https://700kan.com/DyttPlay/98065-2-1.html'))
    #print(m3u8.get_url(url='https://700kan.com/DyttPlay/61116-1-1.html'))
    # print(get_url(url='https://700kan.com/DyttPlay/91973-4-1.html'))
